<script setup lang="ts">
import 'codemirror/mode/javascript/javascript.js';
import type { CmComponentRef } from 'codemirror-editor-vue3';
import CodeMirror from 'codemirror-editor-vue3';
import type { EditorConfiguration } from 'codemirror';
import { reactive, ref } from 'vue';

interface Emits {
  (e: 'change', value: string): void;
}

const emit = defineEmits<Emits>();

const cmRef = ref<CmComponentRef>();
const cmOptions: EditorConfiguration = {
  mode: 'text/javascript',
};
const state = reactive({
  formatterCode: '',
  errMessage: ''
});
const clickFormat = () => {
  if (!state.formatterCode) {
    window.$message?.error('待格式化内容不能为空!');
    return;
  }
  try {
    const format = JSON.parse(state.formatterCode);
    window.$message?.success('格式化成功');
    state.errMessage = '';
    const jsonValue = '```json\n' +
        JSON.stringify(format, null, 2) +
        '\n```'
    emit('change', jsonValue);
  } catch (err) {
    state.errMessage = err.message;
  }
};
</script>

<template>
  <div>
    <div class="flex justify-between">
      <div class="color-#f40">
        {{state.errMessage}}
      </div>
      <n-button @click="clickFormat">格式化</n-button>
    </div>
    <div class="h-100px max-h-360px p2">
      <CodeMirror
          v-model:value="state.formatterCode"
          :options="cmOptions"
          border
          ref="cmRef"
      >
      </CodeMirror>
    </div>
  </div>
</template>

<style scoped>

</style>
